﻿using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using Microsoft.Practices.Unity;
using TrackIT.Common;
using TrackIT.Common.ViewModel;

namespace TrackIT
{  
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr windowHandle, int id, uint modifiers, uint virtualKey);

        private TrackITConfigurationSection _config;

        private readonly TaskViewModel _viewModel;
        public const int WM_HOTKEY_MSG_ID = 0x0312;

        public MainWindow()        
        {
            Visibility = Visibility.Visible;
            Visibility = Visibility.Hidden;
            _viewModel = TrackITContainer.Current.Resolve<TaskViewModel>();
        }
        
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (_viewModel != null)
            {
                if (msg == WM_HOTKEY_MSG_ID)
                {
                    uint key = (uint)(((int)lParam >> 16) & 0xFFFF);
                    ModifierKeys modifier = (ModifierKeys)((int)lParam & 0xFFFF);
                    if (modifier == (ModifierKeys.Control | ModifierKeys.Shift) && key == 'S')
                    {
                        _viewModel.ToggleActionAndShow();
                        Show();
                        Focus();
                    }
                }
            }
            return IntPtr.Zero;            
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            switch( e.Key )
            {
                case Key.F19:   
                case Key.Escape:                    
                case Key.Scroll:
                    Hide();
                    break;
                case Key.Enter:
                    if (_viewModel.CommitCurrentAction())
                        Hide();
                    break;     
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
            if (source != null)
            {
                source.AddHook(WndProc);
                RegisterHotKey(source.Handle, 1, (uint) (ModifierKeys.Control | ModifierKeys.Shift), 'S');
            }
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonDown(e);

            DragMove();
        }

        private void Window_Initialized(object sender, EventArgs e)
        {
            _config = (TrackITConfigurationSection)TrackITContainer.Current.Resolve<TrackITBaseConfigurationSection>();

            if (_config.UseMantis && string.IsNullOrEmpty(_config.Password))
            {
                // prompt for password
                MantisCredentials credentialForm = new MantisCredentials();
                if (credentialForm.ShowDialog() == true)
                {
                    _config.Password = credentialForm.Password;
                    _config.UserName = credentialForm.Username;                    
                    _config.UseMantis = true;
                    _config.Save();
                }
                else
                {
                    _config.UseMantis = false;
                }
            }

            DataContext = _viewModel;
        }
    }   
}

